package com.example.diarymanger.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.diarymanger.bean.ApiResponse;
import com.example.diarymanger.bean.UserBean;
import com.example.diarymanger.mapper.UserMapper;
import com.example.diarymanger.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserBean> implements UserService {

    @Autowired
    private UserMapper userMapper;
    private final int OFFSET = 1000000;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * 注册实现方法
     * @param userBean
     * @return
     */
    @Override
    public ResponseEntity<ApiResponse> register(UserBean userBean) {
        Map<String, Object> response = new HashMap<>();
        System.out.println("userBean=[" + userBean + "]");
        String defaultAvatarPath = "/avatars/touxiang.jpg";
        try {
            Integer maxUid = userMapper.selectMaxUid();
            maxUid = (maxUid == null) ? OFFSET - 1 : maxUid;
            int nextUid = maxUid + 1;
            userBean.setUid(nextUid);
            userBean.setImageLink(defaultAvatarPath);
            int insertResult = baseMapper.insert(userBean);
            if (insertResult > 0) {
                response.put("message", "注册成功");
//                return new ResponseEntity<>(response, HttpStatus.CREATED);
                return new ResponseEntity<>(new ApiResponse(true, "注册成功"), HttpStatus.CREATED);
            } else {
                response.put("error", "注册失败");
//                return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
                logger.error("插入操作未成功");
                return new ResponseEntity<>(new ApiResponse(false, "注册失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("error", "服务器内部错误: " + e.getMessage());
//            return new ResponseEntity<>(response);
            logger.error("注册时发生异常: ", e);
            return new ResponseEntity<>(new ApiResponse(false, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 私有方法，用于生成或验证头像URL
    private String generateAvatarUrl(String imageLink) {
        if (imageLink == null || imageLink.trim().isEmpty()) {
            return "http://localhost:8080/avatars/铅笔_pencil.png";
        }
        // 直接返回imageLink作为头像URL
        //
        //  ，假设imageLink已经是完整路径或相对路径
        return "http://localhost:8080" + imageLink;
    }

    /**
     * 登录实现方法
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserBean login(String username, String password) {
        LambdaQueryWrapper<UserBean> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBean::getUsername, username);
        UserBean user = userMapper.selectOne(queryWrapper);
        //查看用户是否存在
        if (user == null) {
            return null;
        }
        //对比密码是否一致
        if (!user.getPassword().equals(password)) { // 注意：实际应用中应使用加密后的密码比较
            return null;
        }

        // 设置头像URL，这里假设imageLink已经是完整的URL或者需要基于某些规则生成
        user.setImageLink(this.generateAvatarUrl(user.getImageLink()));

        return user;
    }

    /**
     * 更新用户信息实现方法
     * @param userBean
     * @return
     */
    @Override
    public ResponseEntity<ApiResponse> updateUserInfo(UserBean userBean) {
        Map<String, Object> response = new HashMap<>();
        System.out.println("userBean=[" + userBean + "]");
        UpdateWrapper<UserBean> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("uid", userBean.getUid());

        // 直接调用 update 方法进行更新，第一个参数是要更新的数据，第二个参数是更新条件
        boolean updateResult = userMapper.update(userBean, updateWrapper) > 0;

        if (updateResult) {
            return new ResponseEntity<>(new ApiResponse(true, "User information updated successfully."), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new ApiResponse(false, "Failed to update user information."), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
